package com.scalar.chiptrack.adaptor.jsi;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.ScalarException;

import java.io.File;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Locale;

import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Mar 21, 2007
 * Time: 6:59:43 PM
 */
public class JSIShipParser extends JobHandler implements AdaptorConstants
{

    HashMap m_shipDataMap   = new HashMap();

    private String filePath = null;
    private Logger m_parserLogger = null;
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private String m_dataOutputDir      = null;
    private String m_doneDataOutputDir  = null;
    private DBTransaction dbTransaction = null;

    public JSIShipParser() throws ScalarException
    {
        String logDirectory;
        String logFileName = "jsi_ship_parser%u.log";
        String logPrefix = "Jsi_ship_Parser";
        String level = "debug";
        int maxFileSize = 4096 * 500;

        int fileCount = 1;

        //filePath = ConfigManager.getJSIShipSheetDirectory();
        logDirectory = new File(filePath).getParent();
        try
        {
            m_parserLogger = new Logger(logDirectory, logFileName, logPrefix, level, maxFileSize, fileCount);
            ShippedLotDAO.setLogger(m_parserLogger);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws Exception
    {
        new JSIShipParser().execute();
    }

    public void execute() throws Exception
    {
        printVersionInfo();

        boolean success = true;
        ArrayList jsiShipList = new ArrayList();
        jsiShipList = parseJsiShipsheet(filePath);

        if (jsiShipList != null && jsiShipList.size() > 0)
        {
            getJsiShipDetails(jsiShipList);
        }

        // Save Finished Goods shipping info
        try
        {
            if (m_shipDataMap.isEmpty() == false)
            {
                log("Updating shipment Information");
                ShippedLotDAO.saveShippedLot( null, m_shipDataMap.values().iterator());
            }
        }
        catch (Exception e)
        {
            success = false;
            log("ERROR!! ERROR!! ERROR!! Could not update JSI Finished Goods Shipping information into database: " + e);
            e.printStackTrace();
            throw e;
        }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_JSI, false, true, false);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }

        }
        catch ( Exception se )
        {
            success = false;
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
    }

    private ArrayList parseJsiShipsheet(String fileName) throws Exception
    {
        ArrayList jsiShipList       = new ArrayList();
        JSIShipStatus jsiShipStatus = null;
        String partNumber           = null;
        String shippedDate          = null;
        JSIShipStatus shipStatus    = null;
        String billedTo             = null;
        String shippedTo            = null;
        String checkValue;

        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        try
        {
            File shipStatusFile = new File(fileName);

            if (shipStatusFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            log("\nFound " + fileName);
            log("Parsing the file for JSI Ship Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for JSI Ship Report...");

            Workbook workbook = Workbook.getWorkbook(shipStatusFile);
            Sheet sheet = workbook.getSheet("Shipping Report");

            Cell[] row = null;

            for ( int rowCount = 2; rowCount < sheet.getRows(); rowCount++ )
            {
                row             = sheet.getRow(rowCount);
                jsiShipStatus   = new JSIShipStatus();

                if (row != null && row.length > 10 )
                {
                    checkValue = row[9].getContents().trim();

                    if( checkValue != null && checkValue.trim().length() > 0 && !checkValue.startsWith("TOTAL") )
                    {
                        if (row.length > 0)
                        {
                            if (row[0].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setShipDate(null);
                            }
                            else
                            {
                                DateCell dc = (DateCell) row[0];
                                java.util.Date shipDate = null;
                                shipDate = dc.getDate();

                                if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                                {
                                    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                                    cal.setTime(shipDate);
                                    shipDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                    jsiShipStatus.setShipDate(StringUtils.formatDateToString(shipDate));
                                }
                                else
                                {
                                    Calendar cal = new GregorianCalendar();
                                    cal.setTime(shipDate);
                                    shipDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                    jsiShipStatus.setShipDate(StringUtils.formatDateToString(shipDate));
                                }
                            }
                        }
                        if (row.length > 1)
                        {
                            if (row[1].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setJobNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setJobNumber(row[1].getContents().trim());
                            }
                        }
                        if (row.length > 2)
                        {
                            if (row[2].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setPoNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setPoNumber(row[2].getContents().trim());
                            }
                        }
                        if (row.length > 3)
                        {
                            if (row[3].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setSalesOrderNo(null);
                            }
                            else
                            {
                                jsiShipStatus.setSalesOrderNo(row[3].getContents().trim());
                            }
                        }
                        if (row.length > 4)
                        {
                            if (row[4].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setDn(null);
                            }
                            else
                            {
                                jsiShipStatus.setDn(row[4].getContents().trim());
                            }
                        }
                        if (row.length > 5)
                        {
                            if (row[5].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setShipTo(null);
                            }
                            else
                            {
                                jsiShipStatus.setShipTo(row[5].getContents().trim());
                            }
                        }
                        if (row.length > 6)
                        {
                            if (row[6].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setBilledTo(null);
                            }
                            else
                            {
                                jsiShipStatus.setBilledTo(row[6].getContents().trim());
                            }
                        }
                        if (row.length > 7)
                        {
                            if (row[7].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setPartNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setPartNumber(row[7].getContents().trim());
                            }
                        }
                        if (row.length > 8)
                        {
                            if (row[8].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setPartIn(null);
                            }
                            else
                            {
                                jsiShipStatus.setPartIn(row[8].getContents().trim());
                            }
                        }
                        if (row.length > 9)
                        {
                            if (row[9].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setLotNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setLotNumber(row[9].getContents().trim());
                            }
                        }
                        if (row.length > 10)
                        {
                            if (row[10].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setShipQty(null);
                            }
                            else
                            {
                                jsiShipStatus.setShipQty(row[10].getContents().trim());
                            }
                        }
                        if (row.length > 11)
                        {
                            if (row[11].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setOuterBoxes(null);
                            }
                            else
                            {
                                jsiShipStatus.setOuterBoxes(row[11].getContents().trim());
                            }
                        }
                        if (row.length > 12)
                        {
                            if (row[12].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setForwardingAgent(null);
                            }
                            else
                            {
                                jsiShipStatus.setForwardingAgent(row[12].getContents().trim());
                            }
                        }
                        if (row.length > 13)
                        {
                            if (row[13].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setMawb(null);
                            }
                            else
                            {
                                jsiShipStatus.setMawb(row[13].getContents().trim());
                            }
                        }
                        if (row.length > 14)
                        {
                            if (row[14].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setHawb(null);
                            }
                            else
                            {
                                jsiShipStatus.setHawb(row[14].getContents().trim());
                            }
                        }
                        if (row.length > 15)
                        {
                            if (row[15].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setFlight(null);
                            }
                            else
                            {
                                jsiShipStatus.setFlight(row[15].getContents().trim());
                            }
                        }
                        /* Sets previous rows shipdate and  partNumber values*/
                        if( jsiShipStatus.getPartNumber() == null && jsiShipStatus.getShipDate() == null )
                        {
                            for( int i = jsiShipList.size()-1; i >= 0 ; i--)
                            {
                                 shipStatus = (JSIShipStatus)jsiShipList.get(i);

                                if( shipStatus.getPartNumber() != null && shipStatus.getShipDate() != null )
                                {
                                    shippedDate = shipStatus.getShipDate();
                                    partNumber  = shipStatus.getPartNumber();
                                    billedTo    = shipStatus.getBilledTo();
                                    shippedTo   = shipStatus.getShipTo();
                                    break;
                                }
                           }
                           if (shippedDate != null)
                           {
                                jsiShipStatus.setShipDate(shippedDate);
                           }
                           if (partNumber != null)
                           {
                                jsiShipStatus.setPartNumber(partNumber);
                           }
                           if( billedTo != null )
                           {
                               jsiShipStatus.setBilledTo(billedTo);
                           }
                           if( shippedTo != null)
                           {
                               jsiShipStatus.setShipTo(shippedTo);
                           }
                         }

                        jsiShipList.add(jsiShipStatus);
                    }
                }
            }
        }
        catch ( Exception e )
        {
            throw new ScalarException( "Exception " + e );
        }

        return  jsiShipList;
    }

    public void getJsiShipDetails(ArrayList jsiShipList)
    {

        String partNumber           = null;
        String lotNumber            = null;
        JSIShipStatus jsiShipStatus = null;
        ShippedLot shippedLot       = null;

        try
        {
            Iterator jsiFgIterator = jsiShipList.iterator();

            while (jsiFgIterator.hasNext())
            {
                jsiShipStatus = (JSIShipStatus) jsiFgIterator.next();

                partNumber  = jsiShipStatus.getPartNumber();
                lotNumber   = jsiShipStatus.getLotNumber();

                if( partNumber != null && lotNumber != null )
                {
                    shippedLot = (ShippedLot) m_shipDataMap.get(partNumber + lotNumber);

                    if (shippedLot == null)
                    {
                        shippedLot = new ShippedLot();
                        m_shipDataMap.put(partNumber + lotNumber, shippedLot);
                    }
                    int shipQty = 0;
                    if (shippedLot.getShipQty() != null)
                    {
                        try
                        {
                            shipQty = Integer.parseInt(shippedLot.getShipQty());
                        }
                        catch (NumberFormatException ignore) {
                        }
                        try
                        {
                            shipQty += Integer.parseInt(jsiShipStatus.getShipQty());
                        }
                        catch (NumberFormatException ignore) {
                        }
                    }
                    else
                    {
                        try
                        {
                            shipQty = Integer.parseInt(jsiShipStatus.getShipQty());
                        }
                        catch (NumberFormatException ignore)
                        {
                        }
                    }

                    String shipDate         = null;
                    String shippedDate      = null;

                    if( shippedLot.getShipDate() != null )
                    {
                        shipDate = shippedLot.getShipDate() ;
                    }
                    if ( jsiShipStatus.getShipDate() != null && jsiShipStatus.getShipDate().trim().length() > 0 )
                    {
                        shippedDate = jsiShipStatus.getShipDate();
                    }
                    if( ( shippedDate != null ) && ( shipDate != null ) )
                    {
                        java.util.Date tempDate1 = StringUtils.getSQLDate( shippedDate, "MM/dd/yyyy");
                        java.util.Date tempDate2 = StringUtils.getSQLDate( shipDate,"MM/dd/yyyy");
                        if ( tempDate1 != null && tempDate2 != null )
                        {
                            if ( tempDate1.compareTo( tempDate2 ) > 0 )
                            {
                                shippedDate = shipDate;
                            }
                        }
                    }

                    String salesOrderNo = null;
                    if( jsiShipStatus.getSalesOrderNo() != null && "-".equalsIgnoreCase(jsiShipStatus.getSalesOrderNo()))
                    {
                       salesOrderNo = null;
                    }
                    else
                    {
                        salesOrderNo = jsiShipStatus.getSalesOrderNo();
                    }

                    String hawb         = null;
                    if( jsiShipStatus.getHawb() != null && "-".equalsIgnoreCase(jsiShipStatus.getHawb()))
                    {
                         hawb = null;
                    }
                    else
                    {
                         hawb = jsiShipStatus.getHawb();
                    }

                    String mawb         = null;
                    if( jsiShipStatus.getMawb() != null && "-".equalsIgnoreCase(jsiShipStatus.getMawb()))
                    {
                        mawb = null;
                    }
                    else
                    {
                         mawb = jsiShipStatus.getMawb();
                    }

                    shippedLot.setPartNumber(partNumber);
                    shippedLot.setLotNumber(lotNumber);
                    shippedLot.setFabLotNumber(lotNumber);
                    shippedLot.setShipDate(shippedDate);
                    shippedLot.setShipQty(shipQty + "");
                    shippedLot.setCurrentLocation(LOCATION_TYPE_FINISHED_GOODS);
                    shippedLot.setCustomerPO(jsiShipStatus.getPoNumber());
                    shippedLot.setVendorName(VENDOR_NAME_JSI);
                    shippedLot.setMawb(mawb);
                    shippedLot.setHawb(hawb);
                    shippedLot.setInvoiceNumber(jsiShipStatus.getJobNumber());
                    shippedLot.setCustomerSO(salesOrderNo);
                    shippedLot.setNextLocation(jsiShipStatus.getShipTo());
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log("ERROR!ERROR! While parsing the JSI Ship Details" + e);
            System.out.println("ERROR!ERROR! While parsing the JSI Ship Details" + e);
        }


    }

    /**
     *
     * @param message
     */
    private void log(String message)
    {

        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }

    /**
     *
     */
    private void printVersionInfo()
    {
        String info = "\n\n+----------- Running JSI Ship Parser on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+           JSI Ship Interpreter - Beta          \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2007 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println(info);
        log(info);
    } //end of printVersionInfo


}
